$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'projectinfo/projectinfos/list',
        datatype: "json",
        colModel: [
            { label: '项目ID', name: 'projectinfoid', index: 'ProjectInfoId', width: 60, key: true },
            { label: '地区', name: 'areaname', index: 'AreaInfoId', width: 60 },
            { label: '发布者', name: 'useraccount', index: 'CreateUser', width: 80 },
            { label: '项目名称', name: 'projectname', index: 'projectname', width: 80},
            { label: '项目类型', name: 'projecttype', index: 'projecttype', width: 80 ,formatter: function(value, options, row){
                    if(value == null){
                        return "";
                    }
                    if(value == 0){
                        return "工程";
                    }else if(value == 1){
                        return "车队";
                    }else {
                        return "错误！";
                    }
                }},
            { label: '人数', name: 'peoplenum', index: 'PeopleNum', width: 60 },
            { label: '创建时间', name: 'createtime', index: 'CreateTime', width: 80 },
            { label: '处理人', name: 'dealername', index: 'DealUser', width: 60 },
            {
                label: '项目进度',
                name: 'projectprogress',
                index: 'projectprogress',
                width: 50,
                formatter: function (value, options, row) {
                    switch (value) {
                        case 0:
                            return '<span class="label label-warning">进行中</span>';
                        case 1:
                            return '<span class="label label-success">项目完成</span>';
                    }
                }
            },
            { label: '审核状态', name: 'auditstatus', index: 'AuditStatus', width: 70 ,formatter: function(value, options, row){
                    switch(value){
                        case 0:
                            return '<span class="label label-warning">待审核</span>';
                        case 1:
                            return '<span class="label label-success">审核通过</span>';
                        case 2:
                            return '<span class="label label-danger">审核失败</span>';
                    }
                }},
            { label: '软删除', name: 'isdel', index: 'IsDel', width: 70 ,formatter: function(value, options, row){
                    return value === 0 ?
                        '<span class="label label-success">正常</span>' :
                        '<span class="label label-danger">已删除</span>';
                }},
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        postData:{"projectname":vm.projectname},
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
});
//获取token
var token = localStorage.getItem("token");
//富文本框初始化
var E = window.wangEditor;
var editor = new E('#editor');
$.base64.utf8encode = true;
var vm = new Vue({
    el:'#rrapp',
    data:{
        //选择用户界面用户查询参数
        selectUserSearchParam:null,
        //保存选择界面的名称
        userinfo:{useraccount:''},
        //判断当前按钮执行的什么操作的标识（新增，修改，等）
        btn:'index',
        showList: true,
        title: null,
        //项目信息
        projectinfos: {auditstatus:null},
        //项目类型数组
        projecttypes:[],
        //数据字典项目类型查询关键字标识
        urlProjectTypeName:"projectType",
        //项目查询参数
        searchParam:'',
        //项目类型查询
        searchType:'',
        //用户界面保存用户信息
        users:{},
        usershow:true,
        //用户查询的参数
        username:'',
        //每页条数
        userlimit:9,
        //排序
        order:"asc",
        areainfos:{
            parentname:null,
            areaname:null,
            parentid:0,
            columnorder:0
        }
    },
    beforeMount: function(){
        //获取用户列表
        getUserList({username:this.username,limit:this.userlimit,page:1,order:this.order});
    },
    mounted: function(){
        console.log(editor);
        //初始化富文本编辑框
        // editor.customConfig.uploadImgShowBase64 = true
        editor.customConfig.uploadImgServer = '/upload/img';
        editor.customConfig.uploadFileName = 'img';
        editor.customConfig.uploadImgHeaders = {
            'token': token,
        };
        // 配置自定义参数（举例）
        editor.customConfig.uploadImgParams = {
            'type': 1
        };
        editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
        editor.customConfig.uploadImgMaxLength = 5;
        editor.customConfig.onchange = (html) => {
            // var result = htmlEncodeByRegExp(html);
            this.projectinfos.description = html;
        };
        editor.customConfig.uploadImgHooks = {
            success: function (xhr, editor, result) {
                // 图片上传并返回结果，图片插入成功之后触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                var code = result.code;
                if(code == 0){
                    alert("上传成功");
                }else if(code == 500){
                    alert("上传失败");
                }

            },
            fail: function (xhr, editor, result) {
                // 图片上传并返回结果，但图片插入错误时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                alert("图片插入失败");

            },
            error: function (xhr, editor) {
                // 图片上传出错时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                alert("上传出错");
            },
            timeout: function (xhr, editor) {
                // 图片上传超时时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                alert("上传超时");
            },
            // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
            // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
            customInsert: function (insertImg, result, editor) {
                // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
                // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
                var code = result.code;
                // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
                if(code == 500){
                    return;
                }else if(code == 0){
                    var urls = result.data;
                    for(var i =0;i < urls.length;i ++){
                        insertImg(urls[i]);
                    }
                }



                // result 必须是一个 JSON 格式字符串！！！否则报错
            }
        };
        editor.create();
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.btn = 'add';
            vm.projectinfos = {isdel: '0', description: '', auditstatus: 0,projectprogress:0,projecttype:0,viewtimes:0,collecttimes:0};
            // editor.txt.clear();
        },
        update: function (event) {
            var projectinfoid = getSelectedRow();
            if (projectinfoid == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.btn = 'update';
            vm.getInfo(projectinfoid)
        },
        saveOrUpdate: function (event) {
            var url = vm.projectinfos.projectinfoid == null ? "projectinfo/projectinfos/save" : "projectinfo/projectinfos/update";
            if (vm.projectinfos.auditstatus == 1) {//选择通过，并且填写了原因
                vm.projectinfos.cannotpassreason = null;
            }
            var project = vm.projectinfos;
            project.description = $.base64.btoa(vm.projectinfos.description);
            $.ajax({
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("token", token);
                },
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(project),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                            //清空选项中的数据
                            vm.projectinfos = {};
                            vm.userinfo={useraccount:''};
                            vm.btn = 'index';
                        });
                    } else {
                        alert(r.msg);
                    }

                }
            });
        },
        del: function (event) {
            var projectinfoids = getSelectedRows();
            if (projectinfoids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "projectinfo/projectinfos/delete",
                    contentType: "application/json",
                    data: JSON.stringify(projectinfoids),
                    success: function (r) {
                        if (r.code == 0) {
                            var msg = "操作成功";
                            if (!r.msg) {
                                msg = r.msg;
                            }
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (projectinfoid) {
            $.get(baseURL + "projectinfo/projectinfos/info/" + projectinfoid, function (r) {
                var data = r.projectinfos;
                vm.projectinfos = data;
                vm.userinfo.useraccount = vm.projectinfos.useraccount;
                vm.areainfos.parentname = data.areaname;
                //设置富文本内容
                if (data.description) {
                    //传输json数据格式问题，解码
                    data.description = $.base64.atob(data.description, true);
                    editor.txt.html(data.description);
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {"searchParam": vm.searchParam,"projecttype":vm.searchType},
                page: page
            }).trigger("reloadGrid");
            vm.projectinfos = {};
            vm.userinfo = {};
            vm.areainfos = {
                parentname:null,
                areaname:null,
                parentid:0,
                columnorder:0
            }
            editor.txt.clear();
            vm.btn = 'index';
        },
        queryuser: function () {
            getUserList({username:this.username,limit:this.userlimit,page:1,order:this.order});
        },
        ushow: function () {
            if (this.usershow) {
                $("#jqGrid").setGridWidth($(window).width()*0.98);
                $("#desc").width($(window).width()*0.98);
                this.usershow = false;
            } else {
                $("#jqGrid").setGridWidth($(window).width()*0.8);
                $("#desc").width($(window).width()*0.8);
                this.usershow = true;

            }
        },
        previous: function () {
            previous({username:this.username,limit:this.userlimit,page:(this.users.currPage-1),order:this.order});
        },
        next: function () {
            next({username:this.username,limit:this.userlimit,page:(this.users.currPage+1),order:this.order});
        },
        queryprojectbyuser: function (event) {
            var target = event.currentTarget;
            var all = document.getElementById("all");
            //点击全部用户时，更新数据时，顺便显示所有用户
            if(target === all){
                this.username = '';
                getUserList({username:this.username,limit:this.userlimit,page:1,order:this.order})
            }
            var value = target.getAttribute('value');
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                page: page,
                postData: {userinfoid: value}
            }).trigger("reloadGrid");
            vm.showList = true;
            return false;
        },
        selectUser:function () {
            //新增才能选择用户
            if (vm.btn == 'add'){
                //弹窗数据请求的url
                var selectUrl = 'user/userinfos/list';
                //要显示的弹窗数据列
                var tableList = [
                    { label: '用户ID', name: 'userinfoid', index: 'UserInfoId', width: 80, key: true },
                    { label: '用户账户', name: 'useraccount', index: 'UserAccount', width: 60 },
                    { label: '用户名', name: 'username', index: 'UserName', width: 60 },
                    { label: '性别', name: 'usergender', index: 'UserGender',align:"center", width: 20,formatter: function(value, options, row){
                            return value === 0 ? '男' : '女';
                        } },
                    { label: '手机号码', name: 'phonenum', index: 'PhoneNum', width: 80 },
                    { label: '是否Vip', name: 'isvip', index: 'IsVip', width: 40 ,formatter: function(value, options, row){
                            return value === 0 ?
                                '<span class="label label-info">普通用户</span>' :
                                '<span class="label label-primary">VIP用户</span>';
                        }}
                ];
                window.T.selectLayer(selectUrl,tableList,"selectLayer","selectLayerPager");
                layer.open({
                    type: 1,
                    offset: '50px',
                    skin: 'layui-layer-molv',
                    title: "选择用户",
                    area: ['67%', '85%'],
                    shade: 0,
                    shadeClose: false,
                    content: jQuery("#selectUserID"),
                    btn: ['确定', '取消'],
                    btn1: function (index) {
                        var row = window.T.getSelectedRow("selectLayer");
                        if (row != null){
                            //设置显示值
                            vm.userinfo = row;
                            //设置请求值
                            vm.projectinfos.createuser = vm.userinfo.userinfoid;
                        }
                        layer.close(index);
                    }
                });
            }
        },
        selectUserQuery:function () {
            var page = $("#selectLayer").jqGrid('getGridParam','page');
            $("#selectLayer").jqGrid('setGridParam',{
                url:baseURL + "user/userinfos/queryUser" + ((vm.selectUserSearchParam != null)? "?searchParam=" + vm.selectUserSearchParam:""),
                page:page
            }).trigger("reloadGrid");
            vm.selectUserSearchParam = null;
        },
        reason:function(){
            if(this.projectinfos == null){
                return false;
            }
            //审核状态当前为不同就显示
            if(this.projectinfos.auditstatus == 2){
                return true;
            }
            //审核状态为待审核，且有原因就显示
            if(this.projectinfos.auditstatus == 0 && this.projectinfos.cannotpassreason != null && this.projectinfos.cannotpassreason != ""){
                return true;
            }
            return false;
        },
        menuTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择地区",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#menuLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = treeObj.getSelectedNodes();
                    //选择上级菜单
                    vm.projectinfos.areainfoid = node[0].columnid;
                    vm.areainfos.parentname = node[0].areaname;

                    layer.close(index);
                }
            });
        }
    }
});

var setting = {
    async: {
        enable: true, //是否异步,
        type: "POST",
        url: baseURL + "areainfos/areainfos/queryByParentId",
        autoParam: ["columnid"], //传的参数
        dataFilter:ajaxDataFilter,
        dataType:"json"
    },
    view: {
        expandSpeed: "",
        /*  addHoverDom: addHoverDom,
          removeHoverDom: removeHoverDom,*/
        selectedMulti: false,
        showIcon: true,
        showLine: true,
    },
    edit: {
        enable: false
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "columnid",
            pIdKey: "parentid",
            rootPId: 1
        },
        key: {
            name:"areaname",
        },
        keep: {
            parent: true
        }
    }
};

var treeObj = $.fn.zTree.init($("#menuTree"), setting);

function ajaxDataFilter(treeId, parentNode, responseData) {
    var data = responseData.areainfosList;
    return data;
};